// 修复相对路径导入问题的脚本
const fs = require('fs');
const path = require('path');

// 记录需要检查的组件目录结构映射
const componentFolders = {
  'video': ['video-player', 'video-container', 'responsive-video-player', 'video-skeleton', 'video-performance-debug'],
  'navigation': ['nav-bar', 'mobile-nav', 'footer', 'pagination'],
  'video-list': ['videos', 'video-card', 'carousel', 'category-section'],
  'playlist': ['playlist-container', 'mobile-playlist'],
  'filter': ['enhanced-filter', 'filter-section'],
  'vip': ['vip-content', 'vip-only-tip', 'client-vip-tip'],
  'common': ['loading', 'error', 'history-listener', 'rem-adapter', 'html-link']
};

// 记录hooks目录下的文件映射
const hooksFiles = [
  'use-rem-adapter', 
  'use-vip',
  'use-playlist',
  'use-columns'
];

// 获取所有TypeScript和TSX文件
const getAllFiles = (dir, fileList = []) => {
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory() && !filePath.includes('node_modules') && !filePath.includes('.next')) {
      fileList = getAllFiles(filePath, fileList);
    } else if ((filePath.endsWith('.ts') || filePath.endsWith('.tsx') || filePath.endsWith('.js') || filePath.endsWith('.jsx')) && 
               !filePath.includes('node_modules') && !filePath.includes('.next')) {
      fileList.push(filePath);
    }
  });
  
  return fileList;
};

// 分析并修复文件中的相对路径导入
const fixRelativePaths = (filePath) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let updated = false;
    
    // 检查相对路径导入组件 (../components/ 或 ./components/)
    const componentImportRegex = /import .* from ['"](?:\.\.\/|\.\/)(components\/[^'"]+)['"]/g;
    const matches = [...content.matchAll(componentImportRegex)];
    
    for (const match of matches) {
      const originalPath = match[0];
      const componentPath = match[1]; // components/xxx 或 components/folder/xxx
      const pathParts = componentPath.split('/');
      
      // 如果已经有子目录，使用绝对路径
      if (pathParts.length > 2) {
        const folderName = pathParts[1];
        const componentName = pathParts[2].replace('.tsx', '').replace('.ts', '');
        
        // 确认目录结构是否符合我们的组织
        let validFolder = false;
        for (const folder of Object.keys(componentFolders)) {
          if (folder === folderName) {
            validFolder = true;
            break;
          }
        }
        
        if (validFolder) {
          // 使用绝对路径替换相对路径
          const newPath = `import ${originalPath.split(' from ')[0]} from '@/app/components/${folderName}/${componentName}'`;
          content = content.replace(originalPath, newPath);
          updated = true;
        }
      } else {
        // 没有子目录，需要查找组件应该在哪个目录
        const componentName = pathParts[1].replace('.tsx', '').replace('.ts', '');
        let newComponentFolder = null;
        
        // 寻找组件应该在的文件夹
        for (const [folder, components] of Object.entries(componentFolders)) {
          if (components.includes(componentName)) {
            newComponentFolder = folder;
            break;
          }
        }
        
        if (newComponentFolder) {
          // 使用绝对路径替换相对路径
          const newPath = `import ${originalPath.split(' from ')[0]} from '@/app/components/${newComponentFolder}/${componentName}'`;
          content = content.replace(originalPath, newPath);
          updated = true;
        }
      }
    }
    
    // 检查相对路径导入hooks (../hooks/ 或 ./hooks/)
    const hooksImportRegex = /import .* from ['"](?:\.\.\/|\.\/)(hooks\/[^'"]+)['"]/g;
    const hooksMatches = [...content.matchAll(hooksImportRegex)];
    
    for (const match of hooksMatches) {
      const originalPath = match[0];
      const hookPath = match[1]; // hooks/xxx 部分
      const hookName = hookPath.split('/')[1].replace('.tsx', '').replace('.ts', '');
      
      // 如果是匹配到的hooks文件，使用绝对路径
      if (hooksFiles.includes(hookName) || hookName.startsWith('use-') || hookName.startsWith('use')) {
        // 优先检查是否应该使用连字符形式
        let correctHookName = hookName;
        if (hookName.startsWith('use') && !hookName.startsWith('use-') && !hooksFiles.includes(hookName)) {
          // 将驼峰命名转换为连字符命名
          correctHookName = hookName.replace(/([A-Z])/g, '-$1').toLowerCase();
          if (correctHookName.startsWith('use')) {
            correctHookName = 'use' + correctHookName.slice(3);
          }
        }
        
        // 使用绝对路径替换相对路径
        const newPath = `import ${originalPath.split(' from ')[0]} from '@/app/hooks/${correctHookName}'`;
        content = content.replace(originalPath, newPath);
        updated = true;
      }
    }
    
    // 如果文件被更新，则写回
    if (updated) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`已修复相对路径: ${filePath}`);
    }
  } catch (error) {
    console.error(`处理文件 ${filePath} 时出错:`, error);
  }
};

// 主函数
const main = () => {
  console.log('开始修复相对路径导入问题...');
  
  // 获取项目根目录下的所有TypeScript和TSX文件
  const files = getAllFiles(path.resolve(__dirname, '..'));
  
  // 修复每个文件中的相对路径导入
  files.forEach(file => {
    fixRelativePaths(file);
  });
  
  console.log('相对路径导入问题修复完成！');
};

main(); 